import { d_uniShowToast, FINE_LOCATION, MY_LOCATION, ROUTER_OBJ, uniNavigate, uniShowToast } from '../misc';
import {
  didntLoggedIn,
  proGetLocation,
  resetComponentData,
  uniGetStorageSync,
  uniPreviewImage,
  uniSetStorageSync,
  uniSwitchTab
} from '../funcs';
import { TESTING, toggle_TESTING } from '../test';
import { ONLINE_SERVER_MERCHANT, ONLINE_SERVER_USER, tokenRequest, uniRequest } from '../network';
import { USER_ORIENTED } from '../config';

import deepClone from '../../uview-ui/libs/function/deepClone';

let rpStr = 'await';
// 这里只能放比较通用的方法和数据, 保持模块间的清晰
export const appMixin = {
  methods: {
    // 关注房源, param: {id, is_follow}
    followThisThing(houseItem, type = 1) {
      return new Promise((resolve) => {
        if (houseItem.is_follow === 0) {
          // 关注
          let opt = {
            data: {
              house_id: houseItem.id,
              house_type: type,
            },
            success: ({ data }) => {
              houseItem.is_follow = 1;
              d_uniShowToast(
                {
                  title: data.msg,
                },
                false
              );
              resolve();
            },
          };
          tokenRequest('/follow', {}, opt, true);
        } else {
          // 取消关注
          let opt = {
            data: {
              house_id: houseItem.id,
              house_type: type,
            },
            success: ({ data }) => {
              houseItem.is_follow = 0;
              d_uniShowToast(
                {
                  title: data.msg,
                },
                false
              );
              resolve();
            },
          };
          tokenRequest('/cancel_follow', {}, opt, true);
        }
      });
    },

    toPreviewImage(images, current, preCb) {
      preCb && preCb();
      // console.log('预览2',images, current)
      let imageArr;
      if (Array.isArray(images)) {
        imageArr = images;
      } else {
        imageArr = [images];
      }
      uniPreviewImage(imageArr, current);
    },
    // 轮播图查看, 跳转链接
    goPreview(item) {
      // console.log(item)
      if (item.type === 1 && item.img_url) {
        uniSetStorageSync(ROUTER_OBJ, {
          url: item.img_url,
        });
        uniNavigate('/browser/browser');
      } else if (item.type === 2) {
        // 2.跳转房源信息
        
        uniSetStorageSync(ROUTER_OBJ, {
          id: item.house_id,
        });
        let obj = JSON.stringify(uni.getStorageSync('ROUTER_OBJ')) 
        uniNavigate(`/displayDetails/displayDetails?obj=${obj}`);
      } else if (item.type === 3) {
        uniSetStorageSync(ROUTER_OBJ, {
          id: item.build_id,
        });
        uniNavigate('/displayDetails/displayBuildDetails');
      }
    },
    goToAbout() {
      uniRequest(
        '',
        {},
        {
          url: ONLINE_SERVER_MERCHANT + '/about_us',
          success: ({ data }) => {
            if (data.code === 200) {
              // console.log('content: ', data)
              goWith(data.data[0].content);
            }
          },
        }
      );

      function goWith(textContent) {
        uniSetStorageSync(ROUTER_OBJ, {
          title: '关于我们',
          content: textContent,
        });
        uniNavigate('/textDetails');
      }
    },
    toPreventTouchMove() {
      console.log(1);
    },
    handleClick(cb) {
      cb && cb();
    },
    uniBack() {
      if(getCurrentPages().length==1){
        uni.switchTab({
            url: '/pages/home/home'
        });
      }else{
        uni.navigateBack();
      }
      
    },
    uniNavigate(url, opt, cb) {
      uni.navigateTo({
        url:
          '/pages' +
          url /**  路径后可以带参数。参数与路径之间使用?分隔，参数键与参数值用=相连，不同参数用&分隔；
         如 'path?key=value&key2=value2'，path为下一个页面的路径，
         下一个页面的onLoad函数可得到传递的参数 **/,
        success: (res) => {
          // console.log(res)
          cb && cb();
        },
        fail: (res) => {
          console.error(res);
        },
        ...opt,
      });
    },
    tokenNavigate(url) {
      if (didntLoggedIn()) return;
      uniNavigate(url);
    },
    uniSwitchTab(url) {
      uniSwitchTab(url);
    },
    setQuickTest() {
      this.betaTest = false;
      toggle_TESTING();
    },
		
    initLocation(showToast = true) {
      return new Promise((resolve, reject) => {
        this.address = uniGetStorageSync(MY_LOCATION);
        if (!this.address.city) {
          proGetLocation(false)
            .then((res) => {
              if (showToast) uniShowToast('定位成功', false);
              resolve(res);
            })
            .catch((res) => {
              if (showToast) uniShowToast('定位失败, 请手动选择位置');
              // console.log('定位失败: ', res)
              resolve({});
            });
        } else {
          resolve(this.address);
        }
      });
    },
  },
	
  data() {
    return {
      prev_stampThrottle: null,
      now_stampThrottle: null,
      // throttleTimer: null,
      userOriented: USER_ORIENTED,
      requesting: false,
      address: {
        province: '',
        city: '',
        district: '',
      },
      TESTING: TESTING,
      replacementImage: '../../static/images/home/banner1.png',
      rpStr: rpStr,
      // uni-load-more专用属性 START
      status: 'nomore', // 与下面一一对应
      contentText: {
        contentdown: '上拉加载更多', // more
        contentrefresh: '加载中', // loading
        contentnomore: '没有更多', // nomore
      },
      // uni-load-more专用属性 END
    };
  },
  mounted() { },
};

export const houseCardMixin = {
  data() {
    return {
      TESTING: TESTING,
      testingOffShelf: false,
    };
  },
  computed: {
    cardPhoto() {
      let filterStyle = {
        filter: this.offShelf ? 'grayscale(100%)' : '',
      };
      // return {
      //   backgroundImage: 'url(' + this.thumbImage + ')',
      //   ...filterStyle
      // };
      return `background-image: url(${this.thumbImage});`
    },
    tag_bgColor() {
      if (this.offShelf) return 'background-color: #333';
      if (this.tagValue === '租') {
        return '';
      } else if (this.tagValue === '售') {
        return 'background-color: #ba9d61';
      }
    },
    cardOpacity() {
      return this.offShelf ? 'opacity: .5' : '';
    },
    priceTextStyle() {
      return this.offShelf ? 'color: rgb(119,136,153 )' : 'color: #e45a5a;';
    },
  },
  props: {

    // offShelf: {
    //   default() {
    //     return false;
    //   },
    // },
  }
};

export const pullDownRefresh = {
  data() {
    return {
      oldIndex: 0,
      list: [],
      pullTesting: false && TESTING,
			showLoading: true,
    };
  },
  methods: {
    refresh(pullScroll) {
      console.log('refresh', pullScroll);
      this.$nextTick(() => {
        this.$refs.pullScroll.refresh();
      });
    },
    rememberCurrent() {
      this.oldIndex = this.current;
    },
    restoreCurrent() {
      this.current = this.swiperCurrent = this.oldIndex;
    },
    //  可以考虑直接把下面这个方法当成模板, 复制粘贴, 在自己的页面写逻辑
    pullDown(pullScroll) {
			this.showLoading = false;
      let timeout = this.pullTesting ? 10000 : 400;
      setTimeout(async () => {
        if (typeof this.initPageData === 'function') {
          await this.initPageData();
          pullScroll.success();
					this.showLoading = true;
        }
      }, timeout);
    },
    loadData(pullScroll) {
      console.log('loadData', pullScroll);

      let timeout = this.pullTesting ? 5000 : 500;

      setTimeout(() => {
        if (pullScroll.page == 1) {
          this.list = [];
        }
        const curList = [];
        for (let i = this.list.length; i < this.list.length + 20; i++) {
          curList.push(i);
        }
        this.list = this.list.concat(curList);
        if (this.list.length > 60) {
          pullScroll.finish();
        } else {
          pullScroll.success();
        }
      }, timeout);
    },
  },
};

export function resetDataForPullDown() {
  let old = this.current;
  resetComponentData.call(this, () => {
    this.current = this.swiperCurrent = old;
  });
}
export const protocolMixin = {
  components: {
    // ComName: () => import( "./views/ExperienceDetails")
  },
  data() {
    return {
      userProtocol: '',
      privacyProtocol: '',
      USER_ORIENTED: USER_ORIENTED,
    };
  },
  methods: {
    /**
     *
     * @param index 0 用户协议, 1 隐私
     */
    goToDetail(index) {
      if(USER_ORIENTED){
        if (index === 0) {
          // 用户协议
          uniRequest(
            '',
            {},
            {
              url: ONLINE_SERVER_USER + '/user_protocol',
              success: ({ data }) => {
                this.userProtocol = data.data;
                uniSetStorageSync(ROUTER_OBJ, {
                  title: '用户协议',
                  content: this.userProtocol.content,
                });
                uniNavigate('/textDetails');
              },
            }
          );
        } else {
          uniRequest(
            '',
            {},
            {
              url: ONLINE_SERVER_USER + '/privacy_protocol',
              success: ({ data }) => {
                this.privacyProtocol = data.data;
                uniSetStorageSync(ROUTER_OBJ, {
                  title: '隐私协议',
                  content: this.privacyProtocol.content,
                });
                uniNavigate('/textDetails');
              },
            }
          );
        }
      }else{//ONLINE_SERVER_MERCHANT
        if (index === 0) {
          // 用户协议
          uniRequest(
            '',
            {},
            {
              url: ONLINE_SERVER_MERCHANT + '/investment_agreement',
              success: ({ data }) => {
                this.userProtocol = data.data;
                uniSetStorageSync(ROUTER_OBJ, {
                  title: '用户协议',
                  content: this.userProtocol.content,
                });
                uniNavigate('/textDetails');
              },
            }
          );
        } else {
          uniRequest(
            '',
            {},
            {
              url: ONLINE_SERVER_MERCHANT + '/business_private',
              success: ({ data }) => {
                this.privacyProtocol = data.data;
                uniSetStorageSync(ROUTER_OBJ, {
                  title: '隐私协议',
                  content: this.privacyProtocol.content,
                });
                uniNavigate('/textDetails');
              },
            }
          );
        }
      }
    },
  },
};

// 对于tag=租售的房源, 需要把它变成两个
export function split2(list) {
  for (let i = 0, len = list.length; i < len; i++) {
    let any = list[i];

    function toSplit(list) {
      if (any.house_sell_type === 3) {
        any.house_sell_type = 1;
        any.tagName = '租';
        let newItem = deepClone(any);
        newItem.house_sell_type = 2;
        newItem.tagName = '售';
        list.splice(i + 1, 0, newItem);
        len += 1;
      }
    }
    toSplit(list);
  }
}
